//
//  AppDelegate.m
//  BSLCar
//
//  Created by dlios on 15/5/22.
//  Copyright (c) 2015年 lyz. All rights reserved.
//

#import "AppDelegate.h"
#import <FMDatabase.h>
#import "MainViewController.h"
#import "ProCitySelect.h"
@interface AppDelegate ()
{
    UIScrollView *rootScroll;
    NSString *province;
    NSString *city;
    NSString *cityid;
}
@property (nonatomic, retain) FMDatabase *db;
@property (nonatomic ,retain) UILabel *cityLabel;
@property (nonatomic ,retain) UILabel *dateLabel;
@property (nonatomic ,retain) UILabel *weekLabel;
@property (nonatomic ,retain) UILabel *cityidLabel;
@property (nonatomic ,retain) UILabel *tempLabel;
@property (nonatomic ,retain) UILabel *weatherLabel;
@property (retain, nonatomic) NSString *intString;
@end
@implementation AppDelegate
- (void)dealloc
{
    [_db release];
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    [UMSocialData setAppKey:@"556343f267e58ed117001f59"];
    [UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    
    rootScroll = [[UIScrollView alloc] initWithFrame:self.window.frame];
    rootScroll.contentSize = CGSizeMake(self.window.bounds.size.width * 4, self.window.bounds.size.height);
    rootScroll.bounces = NO;
    rootScroll.showsHorizontalScrollIndicator = NO;
    rootScroll.showsVerticalScrollIndicator = NO;
    
    MainViewController *vc = [[MainViewController alloc] init];
    self.window.rootViewController = vc;
    
    //设置所有导航栏的颜色
    [UINavigationBar appearance].barTintColor = [UIColor colorWithRed:1 green:1 blue:0.82 alpha:1];

    //设置所以导航栏是否半透明
    [UINavigationBar appearance].translucent = NO;
    [rootScroll release];
    [vc release];
    [_window release];

    if([CLLocationManager locationServicesEnabled])
    {
        if (!self.myLocationManager){
            self.myLocationManager = [[CLLocationManager alloc]init];
        }
        self.myLocationManager.delegate = self;
//        self.myLocationManager.purpose = @"To provide functionality based on user's current location.";
        //选择定位的方式为最优的状态，他又四种方式在文档中能查到
        self.myLocationManager.desiredAccuracy =kCLLocationAccuracyBest;
        //发生事件的最小距离间隔
        self.myLocationManager.distanceFilter = 1000.0f;
        if([self.myLocationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.myLocationManager requestAlwaysAuthorization]; // 永久授权
            [self.myLocationManager requestWhenInUseAuthorization]; //使用中授权
        }
        [self.myLocationManager startUpdatingLocation];
    }
    _geocoder=[[CLGeocoder alloc]init];
    return YES;
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.myLocationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
            {
                [self.myLocationManager requestWhenInUseAuthorization];
            }
            break;
        default:
            break;
    }
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location = [locations firstObject];//取出第一个位置
    coordinate = location.coordinate;//位置坐标
  //  NSLog(@"经度：%f,纬度：%f",coordinate.longitude,coordinate.latitude);
    //如果不需要实时定位，使用完即使关闭定位服务
    [self.myLocationManager stopUpdatingLocation];
    [self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
//    NSLog(@"%f", coordinate.latitude);
}
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    //反地理编码
    CLLocation *location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks firstObject];
        city = placemark.locality;
        province = placemark.administrativeArea;
        city = [city substringToIndex:city.length - 1];
        province = [province substringToIndex:province.length - 1];
        
        NSArray *proArray = [ProCitySelect selectProvince];
        for (ProvinceDBModel *tempModel in proArray) {
            if ([tempModel.proName isEqualToString:province]) {
                cityid = tempModel.proid;
                break;
            }
        }
        BOOL isE = NO;
        NSArray *cityArray = [ProCitySelect selectCity];
        for (CityDBModel *tempModel in cityArray) {
            if ([tempModel.cityName isEqualToString:city] && [tempModel.proId isEqualToString:cityid]) {
                cityid = tempModel.cityId;
                isE = YES;
                break;
            }
        }
        
        if (isE) {
            province = [NSString stringWithFormat:@"%@/%@", province, city];
        }
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:province forKey:@"proCity"];
        [user setObject:cityid forKey:@"cityid"];
        
        [user setObject:province forKey:@"dingwei"];

//        NSLog(@"%@ %@", city, cityid);
    }];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"地理解码错误息"
                          message:@"地理代码不能识别"
                          delegate:nil
                          cancelButtonTitle:@"Ok"
                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:@"全国" forKey:@"proCity"];
    [user setObject:@"全国" forKey:@"dingwei"];
    [user setObject:@"0" forKey:@"cityid"];
}
#pragma mark 友盟
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
